package com.educatioin.manage.common.filter;

import org.apache.commons.lang3.StringUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 权限过滤器
 */
public class PermissionFilter implements Filter {
    @Override
    public void destroy() {
        
    }
    
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
        throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        HttpServletResponse response = (HttpServletResponse)servletResponse;
        request.setCharacterEncoding("UTF-8");
        
        response.setHeader("Expires", "-1");
        response.setHeader("Cache-Control", "no-cache");
        response.setHeader("Pragma", "no-cache");
        
        String roleName = (String)request.getSession().getAttribute("roleName");
        String userName = (String)request.getSession().getAttribute("userName");
        
        // 获取请求地址
        String requestUrl = request.getRequestURL().toString();
        
        if (StringUtils.isNotEmpty(requestUrl)) {
            if (!requestUrl.contains("/login")) {
                if (StringUtils.isBlank(userName)) {
                    response.sendRedirect(request.getContextPath() + "/html/login.html");
                    return;
                }
            }

//            if (requestUrl.contains("/html/system/")) {
//                // ROLE_ADMIN为超级管理员
//                if (!"ROLE_ADMIN".equals(roleName)) {
//                    response.sendRedirect(request.getContextPath() + "/html/403.html");
//                    return;
//                }
//            }
//            else if (requestUrl.contains("/html/m/")) {
//                // 1：运营管理员
//                if (false) {
//                    response.sendRedirect(request.getContextPath() + "/html/403.html");
//                    return;
//                }
//            }
        }
        
        filterChain.doFilter(request, response);
    }
    
    @Override
    public void init(FilterConfig arg0) throws ServletException {
        
    }
    
}
